<template>
  <div class="booking-calendar">
    <el-card>
      <div class="calendar-header">
        <el-button @click="prevMonth">上月</el-button>
        <h3>{{ currentMonth }}</h3>
        <el-button @click="nextMonth">下月</el-button>
      </div>
      
      <div class="calendar-grid">
        <div class="calendar-weekdays">
          <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
        </div>
        
        <div class="calendar-days">
          <div 
            v-for="day in allDays" 
            :key="day.date.getTime()" 
            class="calendar-day"
            :class="[
              'day-' + day.status,
              { 'current-day': isCurrentDay(day.date) },
              { 'disabled': !isBookable(day.date) }
            ]"
            @click="selectDay(day.date)"
          >
            <div class="day-number">{{ day.date.getDate() }}</div>
            <div v-if="day.bookings && day.bookings.length > 0" class="day-bookings">
              <div v-for="(booking, idx) in day.bookings" :key="idx" class="booking-indicator"></div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="time-slot-selection">
        <h4>选择时间段 (8:00 - 21:00)</h4>
        <div class="time-slots">
          <div 
            v-for="hour in availableHours" 
            :key="hour" 
            class="time-slot"
            :class="{ 
              'selected': selectedHours.includes(hour),
              'unavailable': isHourUnavailable(hour) 
            }"
            @click="toggleHourSelection(hour)"
          >
            {{ hour }}:00 - {{ hour + 1 }}:00
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import moment from 'moment';

// 星期几的缩写
const weekdays = ['日', '一', '二', '三', '四', '五', '六'];

// 当前选中的日期和时间段
const selectedDate = ref(null);
const selectedHours = ref([]);

// 当前月份
const currentMonth = ref('');

// 可用时间段 (8:00 - 21:00)
const availableHours = ref([8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);

// 模拟会议室预订数据
const bookings = ref([
  { date: '2025-05-28', time: 10 },
  { date: '2025-05-28', time: 14 },
  { date: '2025-05-29', time: 9 },
  { date: '2025-05-29', time: 10 },
  { date: '2025-05-29', time: 15 },
  { date: '2025-05-30', time: 13 },
  { date: '2025-05-30', time: 14 },
  { date: '2025-05-30', time: 16 }
]);

// 初始化当前月份
const initCurrentMonth = () => {
  const now = new Date();
  currentMonth.value = now.getFullYear() + '年' + (now.getMonth() + 1) + '月';
  selectedDate.value = new Date();
};

// 获取当月的所有天数
const getDaysOfMonth = (date) => {
  const days = [];
  const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
  const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
  
  // 获取第一天是星期几 (0-6, 0是周日)
  const firstDayOfWeek = firstDay.getDay();
  // 获取最后一天是几号
  const lastDate = lastDay.getDate();
  
  // 填充上个月的空白天数
  for (let i = 0; i < firstDayOfWeek; i++) {
    days.push({
      date: new Date(date.getFullYear(), date.getMonth(), -firstDayOfWeek + i + 1),
      status: 'prev'
    });
  }
  
  // 填充当月的天数
  for (let i = 1; i <= lastDate; i++) {
    const dayDate = new Date(date.getFullYear(), date.getMonth(), i);
    const dayStatus = 'normal';
    
    days.push({
      date: dayDate,
      status: dayStatus,
      bookings: getBookingsForDay(dayDate)
    });
  }
  
  // 填充下个月的空白天数
  const nextMonthDays = 7 - (days.length % 7) || 0;
  for (let i = 1; i <= nextMonthDays; i++) {
    days.push({
      date: new Date(date.getFullYear(), date.getMonth() + 1, i),
      status: 'next'
    });
  }
  
  return days;
};

// 获取某天的预订
const getBookingsForDay = (date) => {
  const dateStr = moment(date).format('YYYY-MM-DD');
  return bookings.value.filter(booking => booking.date === dateStr);
};

// 判断是否是今天
const isCurrentDay = (date) => {
  const today = new Date();
  return (
    date.getFullYear() === today.getFullYear() &&
    date.getMonth() === today.getMonth() &&
    date.getDate() === today.getDate()
  );
};

// 判断日期是否可预订
const isBookable = (date) => {
  const today = new Date();
  // 不能预订过去的日期
  return date >= today;
};

// 判断时间段是否已被预订
const isHourUnavailable = (hour) => {
  if (!selectedDate.value) return false;
  
  const dateStr = moment(selectedDate.value).format('YYYY-MM-DD');
  return bookings.value.some(
    booking => booking.date === dateStr && booking.time === hour
  );
};

// 上个月
const prevMonth = () => {
  const date = new Date(selectedDate.value);
  date.setMonth(date.getMonth() - 1);
  selectedDate.value = date;
  updateCalendar();
};

// 下个月
const nextMonth = () => {
  const date = new Date(selectedDate.value);
  date.setMonth(date.getMonth() + 1);
  selectedDate.value = date;
  updateCalendar();
};

// 更新日历
const updateCalendar = () => {
  currentMonth.value = selectedDate.value.getFullYear() + '年' + (selectedDate.value.getMonth() + 1) + '月';
  allDays.value = getDaysOfMonth(selectedDate.value);
};

// 选择日期
const selectDay = (date) => {
  if (isBookable(date)) {
    selectedDate.value = date;
    // 重置时间段选择
    selectedHours.value = [];
  }
};

// 切换时间段选择
const toggleHourSelection = (hour) => {
  if (isHourUnavailable(hour)) return;
  
  if (selectedHours.value.includes(hour)) {
    selectedHours.value = selectedHours.value.filter(h => h !== hour);
  } else {
    selectedHours.value.push(hour);
    // 按小时排序
    selectedHours.value.sort((a, b) => a - b);
  }
};

// 计算显示的天数
const allDays = ref([]);

// 生命周期钩子
onMounted(() => {
  initCurrentMonth();
  updateCalendar();
});
</script>

<style scoped>
.booking-calendar {
  padding: 20px;
  max-width: 100%;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.calendar-grid {
  
  margin-bottom: 20px;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

.weekday {
  text-align: center;
  font-weight: bold;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10px;
}

.calendar-day {
  aspect-ratio: 1/1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 5px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.calendar-day.disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.day-prev, .day-next {
  opacity: 0.5;
}

.current-day {
  background-color: #e6f7ff;
}

.day-booked {
  background-color: #f5f7fa;
}

.day-number {
  text-align: right;
}

.day-bookings {
  display: flex;
  flex-wrap: wrap;
  gap: 2px;
  margin-top: 5px;
}

.booking-indicator {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: #f56c6c;
}

.time-slot-selection {
  margin-top: 20px;
}

.time-slots {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.time-slot {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

.time-slot.selected {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.time-slot.unavailable {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>